﻿namespace OnlineVideos.RingToneEditor
{
    using System;
    using System.IO;

    public class Id3v2Tag
    {
        private byte[] rawData;
        private long tagEndPosition;
        private long tagStartPosition;

        private Id3v2Tag(Stream input)
        {
           
            input.Position = 0;
            this.tagStartPosition = input.Position;
            BinaryReader reader = new BinaryReader(input);
            byte[] buffer = new byte[10];
            buffer=reader.ReadBytes(10);
            if (((buffer[0] == 0x49) && (buffer[1] == 0x44)) && (buffer[2] == 0x33))
            {
                if ((buffer[5] & 0x40) == 0x40)
                {
                    byte[] buffer2 = reader.ReadBytes(4);
                    int num = buffer2[0] * 0x200000;
                    num += buffer2[1] * 0x4000;
                    num += buffer2[2] * 0x80;
                    num += buffer2[3];
                }
                int count = buffer[6] * 0x200000;
                count += buffer[7] * 0x4000;
                count += buffer[8] * 0x80;
                count += buffer[9];
                byte[] buffer3 = reader.ReadBytes(count);
                if ((buffer[5] & 0x10) == 0x10)
                {
                    byte[] buffer4 = reader.ReadBytes(10);
                }
            }
            else
            {
                input.Position -= 10L;
                throw new FormatException("Not an ID3v2 tag");
            }
            this.tagEndPosition = input.Position;
            input.Position = this.tagStartPosition;
            this.rawData = reader.ReadBytes((int) (this.tagEndPosition - this.tagStartPosition));
        }

        public static Id3v2Tag ReadTag(Stream input)
        {
            try
            {
                return new Id3v2Tag(input);
            }
            catch (FormatException)
            {
                return null;
            }
        }

        public byte[] RawData
        {
            get
            {
                return this.rawData;
            }
        }
    }
}

